import React, { Component } from "react";
import PropTypes from 'prop-types'
import { nanoid } from "nanoid";
import "./index.css";

export default class Header extends Component {

  // 对接收的props进行类型，必要性的限制
  static propTypes = {
    addTodo: PropTypes.func.isRequired
  }

  handleKeyUp = (event) => {
    // 解构赋值
    const { key, target } = event;
    // 判断是否是回车按键
    if (key !== "Enter") return;
    if (target.value.trim() === "") {
      alert("input cannot be null");
      return;
    }
    // 新生成的todo对象
    const todoObj = {
      id: nanoid(),
      name: target.value,
      done: false,
    };
    // 将todoObj传递给App(子传父，调用父组件中传入子组件的回调函数)
    this.props.addTodo(todoObj);
    // 清空输入
    target.value = ''
  };

  render() {
    return (
      <div className="todo-header">
        <input
          type="text"
          placeholder="请输入你的任务名称，按回车键确认"
          onKeyUp={this.handleKeyUp}
        />
      </div>
    );
  }
}
